<template>
  <div>
    <el-form ref="formRef" :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="部门名称">
        <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable style="width: 240px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchEvent">搜索</el-button>
        <el-button type="default" @click="resetEvent">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd()">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
    </el-row>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="deptName" label="部门名称" width="260"></el-table-column>
      <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template v-slot="scope">
          <el-tag type="" v-if="scope.row.status === '0'">正常</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template v-slot="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-p="['system:dept:edit']">修改</el-button>
          <el-button link type="primary" @click="handleAdd(scope.row)" v-p="['system:dept:add']">新增</el-button>
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-if="scope.row.parentId != 0"
            v-p="['system:dept:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="options"
                check-strictly
                :props="treeProps"
                :render-after-expand="false"
              />
              <!-- <Treeselect
                ref="treeselectRef"
                v-model="form.parentId"
                :options="options"
                :show-count="true"
                placeholder="请选择上级部门"
                no-options-text="暂无数据"
                no-children-text="暂无数据"
              /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in dict" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
          <el-button @click="cancel(ruleFormRef)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { DeptItem } from "@/typings";
import type { FormRules, FormInstance } from "element-plus";
import { reactive, ref, onMounted, nextTick } from "vue";
import { addDeptApi, delDeptApi, deptListApi, getDeptByIdApi, updateDeptApi, deptTreeApi } from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";

// 表单
const formRef = ref<FormInstance>();

// 查询参数
const queryParams = reactive({
  deptName: "",
  status: ""
});

const treeProps = ref({
  label: "label",
  value: "id"
});

// 搜索
const searchEvent = () => {
  getDeptList();
};

// 重置
const resetEvent = () => {
  queryParams.deptName = "";
  queryParams.status = "";
  getDeptList();
};

// 根据menuId处理成树形结构，比如handleTree(response.data, "menuId");
const handleTree = (data: any, id: string) => {
  const result: any = [];
  const map = new Map();
  data.forEach((item: any) => {
    map.set(item[id], item);
  });
  data.forEach((item: any) => {
    const parent = map.get(item.parentId);
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      result.push(item);
    }
  });
  return result;
};
// 获取部门列表
const deptList = ref<DeptItem[]>([]);
const getDeptList = async () => {
  try {
    const res = await deptListApi({ ...queryParams });
    if (res.code === 200) {
      deptList.value = handleTree(res.data, "deptId");
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("Error fetching data");
  }
};

// 新增
const handleAdd = async (row?: DeptItem) => {
  try {
    await getDeptTree();
    if (row != undefined) {
      form.value.parentId = row.deptId as any;
      // treeselectRef.value?.select(treeselectRef.value?.getNode(form.value.parentId));
    }
    title.value = "新增部门";
    open.value = true;
  } catch (error) {
    console.error("Error fetching data");
  }
};

// 展开/折叠
const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

const loading = ref(false);
const refreshTable = ref(true);
const isExpandAll = ref(true);
// 弹窗表单
const title = ref("新增部门");
const open = ref(false);
const ruleFormRef = ref<FormInstance>();
const form = ref({
  deptName: "",
  parentId: null,
  deptId: null,
  orderNum: 0,
  leader: "",
  phone: "",
  email: "",
  status: "0",
  icon: ""
});
const rules = reactive<FormRules<keyof typeof form.value>>({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }]
});

// 部门状态
const dict = ref<{ value: string; label: string }[]>([
  { value: "0", label: "正常" },
  { value: "1", label: "停用" }
]);

// 修改
const handleUpdate = async (row: any) => {
  try {
    await getDeptTree();
    const res = await getDeptByIdApi(row.deptId);
    if (res.code === 200) {
      title.value = "修改部门";
      Object.assign(form.value, res.data);
      // treeselectRef.value?.select(treeselectRef.value?.getNode(form.value.parentId));
      open.value = true;
      return;
    }
    ElMessage.error(res.message);
  } catch (error) {
    console.error("修改失败");
  }
};

// 删除
const handleDelete = (row: DeptItem) => {
  try {
    ElMessageBox.confirm("确定删除所勾选的部门吗？删除之后数据将无法恢复", "系统提示", {
      type: "warning"
    }).then(async () => {
      // 调用删除接口
      try {
        const res = await delDeptApi(row.deptId);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          getDeptList();
          return;
        }
        ElMessage.error(res.message);
      } catch (error) {
        ElMessage.error("删除失败，请稍后再试！");
      }
    });
  } catch (error) {
    ElMessage.error("删除失败，请稍后再试！");
  }
};

// 新增接口
const addDept = async (data: any) => {
  try {
    const res = await addDeptApi(data);
    if (res.code === 200) {
      ElMessage.success("新增成功");
      open.value = false;
      // treeselectRef.value?.clear();
      ruleFormRef.value?.resetFields();
      getDeptList();
      return;
    }
    ElMessage.error(res.message);
  } catch (error) {
    ElMessage.error("新增失败，请稍后再试！");
  }
};
// 修改接口
const updateDept = async (data: any) => {
  try {
    const res = await updateDeptApi(data);
    if (res.code === 200) {
      ElMessage.success("修改成功");
      open.value = false;
      // treeselectRef.value?.clear();
      ruleFormRef.value?.resetFields();
      getDeptList();
      return;
    }
    ElMessage.error(res.message);
  } catch (error) {
    ElMessage.error("修改失败，请稍后再试！");
  }
};
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (!valid) return;
    try {
      if (form.value.deptId) {
        // 修改
        updateDept(form.value);
      } else {
        // 新增
        addDept(form.value);
      }
    } catch (error) {
      ElMessage.error("操作失败，请稍后再试！");
    }
  });
};

// 取消表单
// const treeselectRef = ref();
const cancel = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  open.value = false;
  form.value = {} as any;
  // treeselectRef.value?.clear();
};

const options = ref([]);
const getDeptTree = async () => {
  try {
    const res = await deptTreeApi();
    if (res.code === 200) {
      options.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("获取失败，请稍后再试！");
  }
};

onMounted(() => {
  getDeptList();
});
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
